<template>
	<el-main>
		<el-row :gutter="20">
			<el-col :span="10" :offset="6">
				<div class="detail-title">
					<span v-if="$route.query.userId">
						修改
					</span>
					<span v-else>
						新增
					</span>
				</div>
				<el-form :model="form" :rules="rules" ref="form">
					<el-form-item label="用户名" prop="username">
						<el-input 
							:disabled="$route.query.userId?true:false"
							:readonly="$route.query.userId?true:false"
							v-model="form.username" 
							maxlength="10" 
							show-word-limit>
						</el-input>
					</el-form-item>
					<el-form-item label="密码" prop="password" v-if="!$route.query.userId">
						<el-input type="password" v-model="form.password"></el-input>
					</el-form-item>
					<el-form-item label="姓名" prop="realName">
						<el-input v-model="form.realName" maxlength="5" show-word-limit></el-input>
					</el-form-item>
					<el-form-item label="角色" prop="userRole">
						<el-select 
							style="width: 100%;" 
							v-model="form.userRole" 
							multiple 
							:multiple-limit=3 
							placeholder="请选择" 
							@change="changeUserRole">
							<el-option
								v-for="item in roleList"
								:key="item.roleId"
								:label="item.roleName"
								:value="item.roleId">
							</el-option>
						</el-select>
						<div v-if="roleList.length == 0">
							<el-link :underline="false" icon="el-icon-plus" href="/role/detail">
								请前往新增角色
							</el-link>
						</div>
					</el-form-item>
					<div class="dept-content" v-if="!isChoose && $route.query.userId">
						<div><span>*</span> 已选部门：</div>
						<el-tag v-if="form.deptName">
							{{form.deptName}}
						</el-tag>
						<el-tag type="danger" v-else>
							未知错误
						</el-tag>
						<el-button 
							circle 
							icon="el-icon-edit-outline" 
							type="danger"
							size="small"
							@click="isChoose = true" 
							title="修改">
						</el-button>
					</div>
					<el-form-item label="部门" prop="dept_id" v-else>
						<el-cascader
							style="width: 100%;"
							v-model="form.dept_id"
							:props="props"
							@change="chooseDeptId($event)">
						</el-cascader>
					</el-form-item>
					<el-form-item label="状态">
						<el-radio-group v-model="form.status">
							<el-radio border :label="1">启用</el-radio>
							<el-radio border :label="2">禁用</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item>
						<template v-if="!$route.query.userId">
							<el-button type="primary" @click="createUser('form')">
								提交信息
							</el-button>
							<el-button type="warning" native-type="reset">
								重置表单
							</el-button>
						</template>
						<el-button 
							:disabled="form.username == username" 
							type="primary" 
							@click="updateUser('form')" 
							v-else>
							修改信息
						</el-button>
					</el-form-item>
				</el-form>
			</el-col>
		</el-row>
	</el-main>
</template>

<script>
	import { getUsername } from '../../utils/permission.js'
	import { 
		getAvailableRoleList,
		getAvailableTopDepartmentList,
		getChildrenDepartmentListByDeptId,
		getUserById,
		createUser,
		updateUser } from '@/api/user.js'
	export default {
		data() {
			return {
				roleList: {},
				form: {
					userRole: [],
					roleList: [],
					status: 1
				},
				rules: {
					username: [
						{ required: true, message: '请输入用户名', trigger: ['blur', 'change'] }
					],
					password: [
						{ required: true, message: '请输入密码', trigger: ['blur', 'change'] }
					],
					realName: [
						{ required: true, message: '请输入真实名称', trigger: ['blur', 'change'] }
					],
					userRole: [
						{ required: true, message: '请选择角色', trigger: ['blur', 'change'] }
					],
					dept_id: [
						{ required: true, message: '请选择部门', trigger: ['blur', 'change'] }
					]
				},
				props: {
					lazy: true,
					lazyLoad: ((node, resolve) => {
						if (node.level == 0) {
							getAvailableTopDepartmentList().then(function (res) {
								const topDeptList = res.data.map((value, i) => ({
									value: value.deptId,
									label: value.deptName,
									leaf: node.level >= 1
								}));
								let topDepartment = {
									value: 0,
									label: "顶级部门"
								}
								topDeptList.unshift(topDepartment);
								resolve(topDeptList);
							})
						}
						if (node.level != 0) {
							getChildrenDepartmentListByDeptId({'parentId': node.value}).then(function (res) {
								const childrenDeptList = res.data.map((value, i) => ({
									value: value.deptId,
									label: value.deptName,
									leaf: node.level >= 1
								}));
								resolve(childrenDeptList);
							})
						}
					})
				},
				isChoose: false,
				username: getUsername()
			}
		},
		created() {
			this.getAvailableRoleList();
		},
		mounted() {
			if (this.$route.query.userId) {
				this.getUserById(
					this.$route.query.userId
				);
			}
		},
		methods: {
			// 可用的角色列表
			getAvailableRoleList() {
				let _this = this;
				getAvailableRoleList().then(function(res){
					if (res.code === 200) {
						_this.roleList = res.data;
					}
				})
			},
			// 选择用户角色
			changeUserRole(items) {
				if (items.length <= 0) {
					this.$message.error("请赋予用户至少一个角色身份！");
					return false;
				}
				let roleList = [];
				items.forEach((item) => {
					roleList.push({
						'role_id': item
					})
				});
				this.form.roleList = JSON.stringify(roleList);
				this.$forceUpdate(); //强制刷新
			},
			// 选择部门ID
			chooseDeptId(option) {
				this.form.dept_id = option[1];
			},
			// 详情信息
			getUserById(userId) {
				let _this = this;
				getUserById({'userId': userId}).then(function(res){
					if (res.code === 200) {
						_this.form = res.data.user;
						_this.form.roleList = JSON.stringify(res.data.user_roleList);
						// 用户角色
						let list = [];
						res.data.user_roleList.map((x) => {
							_this.roleList.map((k) => {
								if (k.roleId == x.role_id) {
									return list.push(k.roleId)
								}
							})
						})
						_this.form.userRole = list;
					}
				})
			},
			// 创建信息
			createUser(form) {
				this.$refs[form].validate((valid) => {
					let _this = this;
					if (valid) {
						createUser(_this.form).then(function(res){
							if (res.code === 200) {
								_this.$message({
									message: res.msg,
									type: 'success'
								});
								_this.$router.push('./list');
							} else {
								_this.$message.error(res.msg);
							}
						})
					}
				})
			},
			// 修改信息
			updateUser(form) {
				this.$refs[form].validate((valid) => {
					let _this = this;
					if (valid) {
						updateUser(_this.form).then(function(res){
							if (res.code === 200) {
								_this.$message({
									message: res.msg,
									type: 'success'
								});
							} else {
								_this.$message.error(res.msg);
							}
						})
					}
				})
			}
		}
	}
</script>

<style scoped="scoped">
	.dept-content {
		padding-bottom: 20px;
		font-size: 14px;
		color: #606266;
	}
	.dept-content>div {
		padding-top: 10px;
		padding-bottom: 15px;
	}
	.dept-content>div>span {
		color: #F56C6C;
	}
	.dept-content>.el-tag {
		margin-right: 8px;
	}
</style>
